/**
 * Copyright 2014,Peak Tai 台俊峰(taijunfeng_it@sina.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * 		http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.cenluan.tweet.photo;

import java.io.IOException;

import javax.servlet.ServletInputStream;

import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.cenluan.common.OssManager;
import com.cenluan.ext.jfinal.PkController;
import com.cenluan.kit.FileKit;
import com.cenluan.kit.UUIDKit;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.StrKit;

/**
 * 微博照片
 * 
 * @author peak
 * 
 */
public class TweetPhotoController extends PkController {
	/**
	 * 上传
	 * 
	 * @throws IOException
	 */
	@Before(POST.class)
	public void upload() throws IOException {
		String ext = FileKit.getExt(getPara("name"));
		long size = getParaToLong("size");
		if (StrKit.isBlank(ext)) {
			ext = ".jpg";
		}
		ServletInputStream in = getRequest().getInputStream();
		// 保存图片
		String key = "tweet/" + UUIDKit.generateUUID() + ext;
		ObjectMetadata metadata = new ObjectMetadata();
		metadata.setContentType(getPara("type"));
		metadata.setContentLength(size);
		OssManager.saveImage(in, metadata, key);
		// 保存微博图片
		TweetPhoto photo = new TweetPhoto();
		photo.set("id", UUIDKit.generateUUID());
		photo.set("key", key);
		photo.save();
		// 返回信息
		setAttr("id", photo.getStr("id"));
		setAttr("url", OssManager.getImageUrl(key) + "@!tweet-photo-thum");
		renderJson();

	}

	/**
	 * 删除，必须是未关联的微博照片
	 */
	public void delete() {
		TweetPhoto photo = TweetPhoto.dao.findById(getPara());
		if (photo != null && photo.getStr("tweetId") == null) {
			photo.delete();
		}
		renderNull();
	}

	/**
	 * 展示，查看大图
	 */
	public void show() {
		TweetPhoto photo = TweetPhoto.dao.findById(getPara());
		setAttr("photo", photo);
	}
}
